package com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.service.Impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.css.fxfzxczh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzxczh.base.dict.service.DictService;
import com.css.fxfzxczh.common.utils.UpdateUtil;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.entity.Lifeline;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.entity.LifelineType;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.entity.Tree;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.param.LifelineParam;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.repository.LifelineRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.service.LifelineService;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.verify.LifelineExcelVerifyHandler;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.vo.LifelineExcelVo;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.vo.LifelineVO;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.vo.ResultVo;
import com.css.fxfzxczh.modules.fieldWorkManage.noticeManage.entity.Notice;
import com.css.fxfzxczh.modules.fieldWorkManage.noticeManage.param.AuditNotice;
import com.css.fxfzxczh.modules.fieldWorkManage.noticeManage.service.NoticeService;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.entity.ReportPublicField;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.repository.ReportPublicFieldRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.entity.KnowledgeManagement;
import com.css.fxfzxczh.util.*;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/01/30
 * @Description: 生命线工程数据查看
 */
@Service
public class LifelineServiceImpl implements LifelineService {
    @Resource
    LifelineRepository lifelineRepository;
    @Resource
    AttachmentInfoService attachmentInfoService;
    @Resource
    SUserService sUserService;
    @Resource
    NoticeService noticeService;
    @Resource
    DictService dictService;
    @Resource
    LifelineExcelVerifyHandler lifelineExcelVerifyHandler;
    @Resource
    ReportPublicFieldRepository reportPublicFieldRepository;
    @Resource
    EarEveManageService earEveManageService;

    @Override
    public Map<String, Object> getPage(LifelineParam queParams, int curPage, int pageSize) {
        return lifelineRepository.getPage(queParams, curPage, pageSize);
    }

    @Override
    public void exportData(HttpServletResponse response, LifelineParam param) {
        List<Lifeline> list = lifelineRepository.queryByParam(param);
        for (Lifeline lifeline : list) {
            String smxlx = dictService.getValueByDictCodeAndKey("smxlx", lifeline.getLineType());
            lifeline.setLineType(smxlx);
            //交通系统
            if (smxlx.equals("交通系统")){
                String name = dictService.getValueByDictCodeAndKey("jtxt", lifeline.getLineType2());
                lifeline.setLineType2Name(name);
            }
            //供水系统
            if (smxlx.equals("供水系统")){
                String name = dictService.getValueByDictCodeAndKey("gsxt", lifeline.getLineType2());
                lifeline.setLineType2Name(name);
            }
            //输油系统
            if (smxlx.equals("输油系统")){
                String name = dictService.getValueByDictCodeAndKey("syxt", lifeline.getLineType2());
                lifeline.setLineType2Name(name);
            }
            //燃气系统
            if (smxlx.equals("燃气系统")){
                String name = dictService.getValueByDictCodeAndKey("rqxt", lifeline.getLineType2());
                lifeline.setLineType2Name(name);
            }
            //电力系统
            if (smxlx.equals("电力系统")){
                String name = dictService.getValueByDictCodeAndKey("dlxt", lifeline.getLineType2());
                lifeline.setLineType2Name(name);
            }
            //通信系统
            if (smxlx.equals("通信系统")){
                String name = dictService.getValueByDictCodeAndKey("txxt", lifeline.getLineType2());
                lifeline.setLineType2Name(name);
            }
            //水利系统
            if (smxlx.equals("水利系统")){
                String name = dictService.getValueByDictCodeAndKey("slgc", lifeline.getLineType2());
                lifeline.setLineType2Name(name);
            }
            String damage = lifeline.getDamage();
            if (PlatformObjectUtils.isNotEmpty(damage)){
                String name = dictService.getValueByDictCodeAndKey("smxphqk",damage);
                lifeline.setDamage(name);
            }
            String intensity = lifeline.getIntensity();
            if (PlatformObjectUtils.isNotEmpty(intensity)){
                String name = dictService.getValueByDictCodeAndKey("tcld",intensity);
                lifeline.setIntensity(name);
            }

        }
        EasyPoiExcelUtil.exportExcel(list, "生命线数据", "sheet1", Lifeline.class, "生命线数据", response);
    }


    @Override
    public List<Tree> queryLifelineType() {
        List<LifelineType> list1 = lifelineRepository.queryLifelineTypeAll("1");
        List<LifelineType> list2 = lifelineRepository.queryLifelineTypeAll("2");
        List<LifelineType> list3 = lifelineRepository.queryLifelineTypeAll("3");
        ArrayList<Tree> trees = new ArrayList<>();
        //一级
        for (LifelineType lifelineType : list1) {
            if (lifelineType.getLevel().equals("1")) {
                trees.add(assignmentTree(lifelineType));
            }
        }
        //二级
        for (Tree tree : trees) {
            //二级list
            ArrayList<Tree> trees2 = new ArrayList<>();
            for (LifelineType lifelineType : list2) {
                if (lifelineType.getPid().equals(tree.getId())) {
                    Tree tree2 = assignmentTree(lifelineType);
                    //三级list
                    ArrayList<Tree> trees3 = new ArrayList<>();
                    for (LifelineType type : list3) {
                        if (type.getPid().equals(lifelineType.getId())) {
                            Tree tree3 = assignmentTree(type);
                            trees3.add(tree3);
                        }
                    }
                    //三级装入二级
                    tree2.setTree(trees3);
                    //二级装入list
                    trees2.add(tree2);
                }
            }
            tree.setTree(trees2);
        }
        return trees;
    }

    @Override
    public LifelineVO findById(String id) {
        Lifeline lifeline = lifelineRepository.findById(id);
        LifelineVO lifelineVO = new LifelineVO();
        UpdateUtil.copyNullProperties(lifeline, lifelineVO);
        if (PlatformObjectUtils.isNotEmpty(lifeline.getEnclosurePhoto())) {
            lifelineVO.setEnclosurePhoto(attachmentInfoService.queryFile(lifeline.getEnclosurePhoto()));
        }
        if (PlatformObjectUtils.isNotEmpty(lifeline.getEnclosureVideo())) {
            lifelineVO.setEnclosureVideo(attachmentInfoService.queryFile(lifeline.getEnclosureVideo()));
        }
        if (PlatformObjectUtils.isNotEmpty(lifeline.getEnclosureAudio())) {
            lifelineVO.setEnclosureAudio(attachmentInfoService.queryFile(lifeline.getEnclosureAudio()));
        }
        if (PlatformObjectUtils.isNotEmpty(lifeline.getEnclosureAlbum())) {
            lifelineVO.setEnclosureAlbum(attachmentInfoService.queryFile(lifeline.getEnclosureAlbum()));
        }
        return lifelineVO;
    }

    //批量审核
    @Override
    public void batchAudit(List<Lifeline> lifeline) {
        ArrayList<AuditNotice> list = new ArrayList<>();
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        for (Lifeline lifeline1 : lifeline) {
            //单条审核
            lifelineRepository.audit(lifeline1.getXlrId(), lifeline1.getSuggestion(), lifeline1.getStatus());
            if (lifeline1.getStatus().equals("1")){
                AuditNotice auditNotice = getAuditNotice(lifeline1, sUser);
                list.add(auditNotice);
            }
        }
        if (list.size()>0) {
            String s = noticeService.auditNotice(list);
        }
    }

    //转换实体
    public AuditNotice getAuditNotice(Lifeline lifeline, SUser sUser) {
        AuditNotice auditNotice = new AuditNotice();
        auditNotice.setXnmId(UUID.randomUUID().toString().replaceAll("-", ""));
        auditNotice.setDelFlag(YNEnum.N.toString());
        auditNotice.setCreateUser(sUser.getUserId());
        auditNotice.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        auditNotice.setXsemId(lifeline.getXsemId());
        //通知类型
        auditNotice.setNoticeType("1");
        //通知名称
        auditNotice.setNoticeName("【" + lifeline.getLifelineCode() + "】的生命线工程调查数据审核未通过");
        //通知内容
        auditNotice.setNoticeContent("数据编号为【" + lifeline.getLifelineCode() + "】的生命线工程调查数据审核未通过,未通过原因【" + lifeline.getSuggestion() + "】");
        //发起人
        auditNotice.setSponsor(sUser.getUserName());
        //通知时间
        auditNotice.setNoticeTime(auditNotice.getCreateTime());
        //通知范围
        auditNotice.setNoticeRange(lifeline.getInvestigator());
        //被通知人id
        auditNotice.setBeNotified(lifeline.getInvestigatorId());
        return auditNotice;
    }


    @Override
    public void updateById(Lifeline param) {
        String userID = PlatformSessionContext.getUserID(); // 获取当前登录用户
        param.setUpdateUser(userID);
        param.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        lifelineRepository.updateById(param);
    }

    @Override
    public Map<String, Object> importExcel(MultipartFile file, ResultVo resultVo) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(2);
        //params.setImportFields(new String[]{"省","市","区(县)","详细地址","抽样点名称","房屋单体名称","经度","纬度","结构类型","破坏情况","建筑面积（平方米）","用途类型","是否为典型房屋","损失值（元）","室内外财产损失比例","是否为中高档装修","具体描述情况"});
        params.setNeedVerify(true);
        params.setVerifyHandler(lifelineExcelVerifyHandler);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String userName = sUser.getUserName();
            //EarEveManage currentEvent = earEveManageService.getCurrentEvent();//获取当前地震事件
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<LifelineExcelVo> result = ExcelImportUtil.importExcelMore(inputStream, LifelineExcelVo.class, params);
            List<LifelineExcelVo> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for (LifelineExcelVo lifeline : failList) {
                    errorMsg.append("<font size='4px' ><br>").append("第").append(lifeline.getRowNum() + 1).append("行： ").append(lifeline.getErrorMsg()).append("</font>");
                }
                map.put("res", res);
                map.put("mess", errorMsg);
                return map;
            }
            List<LifelineExcelVo> resultData = result.getList();//解析excel
            for(LifelineExcelVo lifelineExcelVo : resultData){
                Lifeline lifeline = new Lifeline();
                SpringUtil.copyPropertiesIgnoreNull(lifelineExcelVo, lifeline);
                String uuid = UUIDGenerator.getUUID();
                lifeline.setXlrId(uuid);

//                lifeline.setXstmId(resultVo.getXstmId());
                lifeline.setSampleName(resultVo.getSamplingPointName());
                lifeline.setSampleId(resultVo.getSamId());
                //未审核
                lifeline.setStatus("2");
                //todo 生命线编号生成 (没有接口)
                EarEveManage currentEvent = earEveManageService.getCurrentEvent();
                String samplingPointHouseCode = getLifeLineCode(currentEvent.getEventCode());
                lifeline.setLifelineCode(samplingPointHouseCode);
                lifeline.setXsemId(currentEvent.getXsemId());
                //生命线类型  一级
                String lineType1 = lifeline.getLineType();//未转换成key之前的生命线类型一级
                String lineType = dictService.getKeyByDictCodeAndValue("smxlx", lifeline.getLineType());//从数据字典中获取key
                lifeline.setLineType(lineType);
                //生命线类型  二级
                String lineType2 = "";
                if(lineType1.equals("交通系统")){
                    lineType2 = dictService.getKeyByDictCodeAndValue("jtxt", lifeline.getLineType2());
                }else if(lineType1.equals("供水系统")){
                    lineType2 = dictService.getKeyByDictCodeAndValue("gsxt", lifeline.getLineType2());
                }else if(lineType1.equals("输油系统")){
                    lineType2 = dictService.getKeyByDictCodeAndValue("syxt", lifeline.getLineType2());
                }else if(lineType1.equals("燃气系统")){
                    lineType2 = dictService.getKeyByDictCodeAndValue("rqxt", lifeline.getLineType2());
                }else if(lineType1.equals("电力系统")){
                    lineType2 = dictService.getKeyByDictCodeAndValue("dlxt", lifeline.getLineType2());
                }else if(lineType1.equals("通信系统")){
                    lineType2 = dictService.getKeyByDictCodeAndValue("txxt", lifeline.getLineType2());
                }else if(lineType1.equals("水利工程")){
                    lineType2 = dictService.getKeyByDictCodeAndValue("slgc", lifeline.getLineType2());
                }
                lifeline.setLineType2(lineType2);

                String damage = dictService.getKeyByDictCodeAndValue("smxphqk", lifeline.getDamage());
                lifeline.setDamage(damage);
                String intensity = dictService.getKeyByDictCodeAndValue("tcld", lifeline.getIntensity());
                lifeline.setIntensity(intensity);
                lifeline.setStatus("0");
                lifeline.setDelFlag("0");
                lifeline.setCreateUser(userId);
                lifeline.setCreateTime(new Date());
                lifeline.setInvestigator(userName);
                res = lifelineRepository.save(lifeline);

                //保存专门维护省市区县的表
                ReportPublicField reportPublicField = new ReportPublicField();
                reportPublicField.setXlrmId(uuid);
                reportPublicField.setXsemId(resultVo.getXsemId());
                reportPublicField.setProvince(lifelineExcelVo.getProvince());
                reportPublicField.setCity(lifelineExcelVo.getCity());
                reportPublicField.setCounty(lifelineExcelVo.getDistrict());
                reportPublicField.setCreateUser(userId);
                reportPublicField.setDelFlag("0");
                reportPublicFieldRepository.save(reportPublicField);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        map.put("res",res);
        return map;
    }

    //新增
    @Override
    public String save(Lifeline param) {
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        param.setXlrId(id);
        param.setDelFlag(YNEnum.N.toString());
        param.setCreateUser(PlatformSessionContext.getUserID());
        param.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        param.setInvestigationTime(PlatformDateUtils.getCurrentTimestamp());
        param.setSubmit(YNEnum.N.toString());
        param.setGeom("POINT("+param.getLongitude()+" " +param.getLatitude()+")");
        String userID = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        param.setInvestigator(sUser.getUserName());
        lifelineRepository.save(param);
        return id;
    }

    //提交
    @Override
    public void submit(List<String> ids) {
        lifelineRepository.submit(ids);
    }

    @Override
    public void batchDelete(List<String> ids) {
        lifelineRepository.batchDelete(ids);
    }

    @Override
    public String getLifeLineCode(String eventCode) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        eventCode=currentEvent.getEventCode();
        StringBuilder lifeLineCode = new StringBuilder(eventCode + "SMXGC");
        DecimalFormat decimalFormat = new DecimalFormat("000");
        String num = "";

        String maxNum = lifelineRepository.getMaxNum(lifeLineCode.toString());
        if (PlatformObjectUtils.isEmpty(maxNum)) {
            int i = 1;
            num = decimalFormat.format(i);
        } else {
            String substring = maxNum.substring(maxNum.length()-3);
            num = decimalFormat.format(Integer.parseInt(substring) + 1);
        }
        return lifeLineCode.append(num).toString();
    }

    //赋值
    private Tree assignmentTree(LifelineType lifelineType) {
        Tree tree = new Tree();
        tree.setId(lifelineType.getId());
        tree.setPid(lifelineType.getPid());
        tree.setLifelineTypeName(lifelineType.getLifelineTypeName());
        tree.setLevel(lifelineType.getLevel());
        tree.setDamageLevel(lifelineType.getDamageLevel());
        tree.setDamageCondition(lifelineType.getDamageCondition());
        return tree;
    }
}
